package main

import (
	"context"
	"fmt"
	"gitee.com/sunzheng86/gotask"
	 log "github.com/sirupsen/logrus"
	"os"
	"sync"
	"time"
)

const (
	uniqueJobName = "a-unique-job-name"
	redisURL      = "redis://10.185.129.33:6379/0"
	queueName     = "job-queue-name"
)

func Handler1(taskid string, args gotask.ArgsMap) (gotask.ArgsMap, error) {
	wg := sync.WaitGroup{}
    timmertick := time.After(20 * time.Second)
    out := false
	wg.Add(1)

    go  func( ){
    	count := 0
    	for !out {
    		count++
			fmt.Printf("handle1 [%s] running %d seconds\n",taskid, count)
			time.Sleep(1 * time.Second)
		}
		fmt.Printf("[%s]out is %v, break\n",taskid,out)
    	wg.Done()
	}()


    select {
    case <- timmertick:
    	out = true
    }

	wg.Wait()
	fmt.Printf("task[%s] finishd\n",taskid)

	return args, nil
}
func Handler2(taskid string, args gotask.ArgsMap) (gotask.ArgsMap, error) {
	wg := sync.WaitGroup{}
	timmertick := time.After(30 * time.Second)
	out := false
	wg.Add(1)

	go  func( ){
		count := 0
		for !out {
			count++
			fmt.Printf("handle2 [%s] running %d seconds\n",taskid, count)
			time.Sleep(1 * time.Second)
		}
		fmt.Printf("[%s]out is %v, break\n",taskid, out)
		wg.Done()
	}()


	select {
	case <- timmertick:
		out = true
	}

	wg.Wait()
	fmt.Printf("[%s] finishd\n", taskid)

	return args, nil
}

func register() {
	// if handler1 failed, the task will stop, but if handler2 failed(return a non-nil error)
	// handler2 will be retry 3 times, and sleep 100 ms each time
	gotask.Register("handler1", Handler1)
	gotask.Register("handler2", Handler2)
}

func worker() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	gotask.Run(ctx, 6, queueName)
}

func main() {
	log.SetLevel(log.InfoLevel)
	log.SetReportCaller(true)
	log.SetOutput(os.Stdout)
	// set broker
	if err := gotask.UseRedisBroker(redisURL, gotask.WithRedisTaskTTL(1000)); err != nil {
		fmt.Printf("尝试使用redis数据库报错：%s",err)
		return
	}
	register()
	worker()
}
